/**
 * Copyright (C) 2015 kmhc-framework-base Project
 *               Author: Chris
 *               Date: 2015年11月23日
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.zmq.ha.client.resource;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zmq.ha.client.core.Context;
import com.zmq.ha.client.util.TimeUtil;


/**
 * Name: RetryableContext.java
 * ProjectName: [kmhc-framework-base]
 * Package: [com.kmhc.framework.rabbitmq.recover.resource.RetryableContext.java]
 * Description: TODO  
 * 
 * @since JDK1.7
 * @see
 *
 * @author: Chris
 * @date: 2015年11月23日 下午2:18:23
 *
 * Update-User: @author
 * Update-Time:
 * Update-Remark:
 * 
 * Check-User:
 * Check-Time:
 * Check-Remark:
 * 
 * Company: kmhc
 * Copyright: kmhc
 */
public abstract class RetryableContext {
	
	private static final  Logger log = LoggerFactory.getLogger(RetryableContext.class);
	
	public static final AtomicInteger retryCount = new AtomicInteger(3);
	
	public static volatile long lastTryTime = 1;
	
	public static volatile boolean isRetrySet = true;
	
	public static final int retryFrequency = 500;
	
	public static volatile int retryPublishTime = 0;
	
	//重新连接重试工具   // TODO best to be MBean by use JMX to wake up thread...
	public static final ReentrantLock lock = new ReentrantLock();
	
	public static final Condition retryCondition = lock.newCondition();
	
	public static void increaseRetryCount(){
		retryCount.incrementAndGet();
	}
	
	public static boolean isOverTetryCount(){
		 return Context.retryCount < retryCount.get();
	}
	
	protected static void waitForRetry(){
		lock.lock();
		try {
			retryCondition.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally{
			lock.unlock();
		}
	}
	
	protected static void signalForRetry(){
		lock.lock();
		try {
			log.info(TimeUtil.getDateAndTimeNow()+" signalAllReTry...");
			retryCondition.signalAll();
			retryCount.set(0);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}
}
